package com.example.accessibilityhelper

import android.accessibilityservice.AccessibilityService
import android.view.accessibility.AccessibilityEvent
import java.util.ArrayDeque

object Dispatcher {
    private val readyTasks = ArrayDeque<Task>()
    private var runningTask: Task? = null
    private var finishedTasks = ArrayDeque<Task>()

    private fun poll(): Task? {
        return readyTasks.poll()
    }

    fun offerAndPromote(task: Task) {
        readyTasks.offerLast(task)
        promote()
    }

    private fun promote() {
        if (runningTask == null) {
            runningTask = poll()
        }
    }

    fun finishAndPromote(task: Task) {
        runningTask = null
        finishedTasks.offerLast(task)
        promote()
    }

    fun dispatch(service: AccessibilityService, event: AccessibilityEvent) {
        runningTask?.tryMatchStepOnAccessibilityEvent(service, event)
    }
}